﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Devmil.MVVM.Notification;

namespace Devmil.MVVM.Sample.ViewModel
{
    public class MainViewModel : IFireNotifyPropertyChanged
    {
        private ObservableCollection<ContactViewModel> _Contacts;
        public ObservableCollection<ContactViewModel> Contacts
        {
            get
            {
                using (this.Track(p => p.Contacts))
                    return _Contacts;
            }
        }

        private ContactViewModel _CurrentContact;
        public ContactViewModel CurrentContact
        {
            get
            {
                using (this.Track(p => p.CurrentContact))
                {
                    if (SelectedContactIndex < Contacts.Count)
                        return Contacts[SelectedContactIndex];
                    return null;
                }
            }
        }

        private int _SelectedContactIndex;
        public int SelectedContactIndex
        {
            get
            {
                using (this.Track(p => p.SelectedContactIndex))
                    return _SelectedContactIndex;
            }
            set
            {
                this.SetPropertyValue(p => p.SelectedContactIndex, ref _SelectedContactIndex, value);
            }
        }

        public string CurrentContactNameString
        {
            get
            {
                using (this.Track(p => p.CurrentContactNameString))
                {
                    if (CurrentContact != null)
                        return CurrentContact.Name;
                    return "No Contact selected";
                }
            }
        }

        public MainViewModel()
        {
            _Contacts = new ObservableCollection<ContactViewModel>();
            _Contacts.Add(new ContactViewModel() { Name = "Devmil" });
            _Contacts.Add(new ContactViewModel() { Name = "Michael" });
            _Contacts.Add(new ContactViewModel() { Name = "John" });
            _Contacts.Add(new ContactViewModel() { Name = "Michelle" });
            _Contacts.Add(new ContactViewModel() { Name = "Peter" });
            _Contacts.Add(new ContactViewModel() { Name = "Susan" });
            this.RegisterCollection(p => p.Contacts);
        }

        public void FireNotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
